package cn.com.thingo.shyintelligent.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.exception.ErrorCode;
import com.videogo.exception.InnerException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.realplay.RealPlayStatus;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.LocalInfo;
import com.videogo.util.MediaScanner;
import com.videogo.util.SDCardUtil;
import com.videogo.util.Utils;
import com.videogo.widget.RingView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTouch;
import cn.com.thingo.shyintelligent.R;
import cn.com.thingo.shyintelligent.app.Constants;
import cn.com.thingo.shyintelligent.app.EzHttpConstants;
import cn.com.thingo.shyintelligent.base.BaseActivity;
import cn.com.thingo.shyintelligent.base.contract.EzCameraContract;
import cn.com.thingo.shyintelligent.model.bean.EzStatementBean;
import cn.com.thingo.shyintelligent.model.db.UserInfo;
import cn.com.thingo.shyintelligent.presenter.EzCameraPresenter;
import cn.com.thingo.shyintelligent.util.ActivityUtils;
import cn.com.thingo.shyintelligent.util.AudioPlayUtil;
import cn.com.thingo.shyintelligent.util.EZUtils;
import cn.com.thingo.shyintelligent.util.LogUtil;
import cn.com.thingo.shyintelligent.util.SPUtils;
import cn.com.thingo.shyintelligent.util.ToastUtil;
import cn.com.thingo.shyintelligent.util.VerifyCodeInput;
import cn.com.thingo.shyintelligent.widget.PlayerLoadingTextView;
import cn.com.thingo.shyintelligent.widget.WaitDialog;

public class EzCameraActivity extends BaseActivity<EzCameraPresenter> implements EzCameraContract.View {
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_del)
    TextView mTvDel;
    @BindView(R.id.sv_realplay)
    SurfaceView mSurfaceView;
    @BindView(R.id.iv_play)
    ImageView mIvPlay;
    @BindView(R.id.iv_pause)
    ImageView mIvpause;
    @BindView(R.id.realplay_loading)
    PlayerLoadingTextView mPlayerLoadingTextView;
    @BindView(R.id.iv_rotate)
    ImageView mIvRotate;
    @BindView(R.id.iv_microphone)
    ImageView mIvMicrophone;
    @BindView(R.id.iv_camera)
    ImageView mIvCamera;
    @BindView(R.id.iv_voice)
    ImageView mIvVoice;
    @BindView(R.id.tv_prompt)
    TextView mTvPrompt;
    @BindView(R.id.ll_monitor)
    LinearLayout mLlmonitor;
    private UserInfo mUserInfo;
    private EZDeviceInfo mEZDeviceInfo;
    private EZPlayer mEZPlayer;
    private PlayerHandler mPlayerHandler;
    private String mDeviceSerial;
    private String mVerifyCode;
    private AudioPlayUtil mAudioPlayUtil;
    private EZOpenSDK mEZOpenSDK;
    private LocalInfo mLocalInfo;
    private SPUtils mSPUtils;
    private boolean isPlay;
    private boolean mIsOnTalk;
    private PopupWindow mTalkPopupWindow = null;
    private RingView mTalkRingView = null;
    private Button mTalkBackControlBtn = null;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_ez_camera;
    }

    @Override
    protected void initEventAndData() {
        mUserInfo = UserInfo.getInstance();
        mEZOpenSDK = EZOpenSDK.getInstance();
        mLocalInfo = LocalInfo.getInstance();
        mSPUtils = SPUtils.newInstance();
        mAudioPlayUtil = AudioPlayUtil.getInstance((Application) mContext.getApplicationContext());
        if (mLocalInfo.isSoundOpen()) {
            mIvVoice.setImageResource(R.mipmap.player_voice_open);
        } else {
            mIvVoice.setImageResource(R.mipmap.player_voice_close);
        }
        mEZDeviceInfo = getIntent().getParcelableExtra(Constants.TAG_ROOM);
        if (mEZDeviceInfo != null) {
            mTvTitle.setText(mEZDeviceInfo.getDeviceName());
        }

        showDevice();
    }

    private void showDevice() {
      if (mEZDeviceInfo!=null){
          int status = mEZDeviceInfo.getStatus();
          if (status == 1) {
              mIvPlay.setVisibility(View.VISIBLE);
              mIvpause.setVisibility(View.GONE);
              mPlayerLoadingTextView.setVisibility(View.GONE);
              mTvPrompt.setVisibility(View.GONE);
          } else {
              mIvPlay.setVisibility(View.GONE);
              mIvpause.setVisibility(View.GONE);
              mPlayerLoadingTextView.setVisibility(View.GONE);
              mTvPrompt.setVisibility(View.VISIBLE);
              mTvPrompt.setText("设备不在线!");
          }
          mDeviceSerial = mEZDeviceInfo.getDeviceSerial();
          mVerifyCode = mSPUtils.getString(mDeviceSerial);

      }
    }



    @Override
    public void viewDelEzDevicePermissionResult(EzStatementBean ezStatementBean) {
        String code = ezStatementBean.getCode();
        switch (code) {
            case EzHttpConstants.OPERATE_SUCCESSFULLY_CODE:
                new DeleteDeviceTask().execute();
                break;
            default:
                ToastUtil.shortShow(ezStatementBean.getMsg());
                break;
        }
    }

    /**
     * 删除设备任务
     */
    private class DeleteDeviceTask extends AsyncTask<Void, Void, Boolean> {

        private Dialog mWaitDialog;

        private int mErrorCode = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mEZOpenSDK.setAccessToken(mUserInfo.getAccessToken());
            mWaitDialog = new WaitDialog(EzCameraActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
            mWaitDialog.setCancelable(false);
            mWaitDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (!ConnectionDetector.isNetworkAvailable(EzCameraActivity.this)) {
                mErrorCode = ErrorCode.ERROR_WEB_NET_EXCEPTION;
                return false;
            }

            try {
//            	EZCameraInfo cameraInfo = params[0];
                mEZOpenSDK.deleteDevice(mDeviceSerial);
                return true;
            } catch (BaseException e) {
                ErrorInfo errorInfo = (ErrorInfo) e.getObject();
                mErrorCode = errorInfo.errorCode;
                LogUtil.e(errorInfo.toString());

                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
           mEZOpenSDK.setAccessToken(mUserInfo.getRamAccessToken());
            mWaitDialog.dismiss();
            if (result) {
                ToastUtil.show("删除成功");
                sendBroadcast(new Intent(Constants.ACTION_ADD_DEVICE));
                finish();
            } else {
                switch (mErrorCode) {
                    case ErrorCode.ERROR_WEB_SESSION_ERROR:
                        ActivityUtils.handleSessionException(EzCameraActivity.this);
                        break;
                    case ErrorCode.ERROR_WEB_HARDWARE_SIGNATURE_ERROR:
                        ActivityUtils.handleSessionException(EzCameraActivity.this);
                        break;
                    case ErrorCode.ERROR_WEB_NET_EXCEPTION:
                        ToastUtil.show(R.string.alarm_message_del_fail_network_exception);
                        break;
                    case ErrorCode.ERROR_WEB_DEVICE_VALICATECODE_ERROR:
                        ToastUtil.show(R.string.verify_code_error);
                    default:
                        ToastUtil.show("删除失败,未知错误");
                        break;
                }

            }

        }
    }


    class PlayerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code = msg.what;
            switch (code) {
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                    mIvPlay.setVisibility(View.GONE);
                    mIvpause.setVisibility(View.GONE);
                    mPlayerLoadingTextView.setVisibility(View.GONE);
                    mTvPrompt.setVisibility(View.GONE);
                    mSPUtils.put(mDeviceSerial, mVerifyCode);
                    isPlay = true;
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                    mIvPlay.setVisibility(View.VISIBLE);
                    mIvpause.setVisibility(View.GONE);
                    mPlayerLoadingTextView.setVisibility(View.GONE);
                    mTvPrompt.setVisibility(View.GONE);
                    mVerifyCode = null;
                    isPlay = false;
                    ToastUtil.shortShow(((ErrorInfo)msg.obj).description);
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_STOP_SUCCESS:
                    mIvPlay.setVisibility(View.VISIBLE);
                    mIvpause.setVisibility(View.GONE);
                    mPlayerLoadingTextView.setVisibility(View.GONE);
                    mTvPrompt.setVisibility(View.GONE);
                    isPlay = false;
                    break;

                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_SUCCESS:
                    openTalkPopupWindow(true);
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_STOP:
                    handleVoiceTalkStoped(false);
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_FAIL:
                    ErrorInfo errorInfo = (ErrorInfo) msg.obj;
                    handleVoiceTalkFailed(errorInfo);
                    break;
            }
        }
    }

    /**
     * 打开对讲控制窗口
     *
     * @see
     * @since V1.8.3
     */
    private void openTalkPopupWindow(boolean showAnimation) {
        if (!isPlay) {
            return;
        }
        closeTalkPopupWindow(false, false);
        LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewGroup layoutView = (ViewGroup) layoutInflater.inflate(R.layout.realplay_talkback_wnd, null, true);
        layoutView.setFocusable(true);
        layoutView.setFocusableInTouchMode(true);
        layoutView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg1 == KeyEvent.KEYCODE_BACK) {
                    closeTalkPopupWindow(true, false);
                }
                return false;
            }
        });


        ImageButton talkbackCloseBtn = (ImageButton) layoutView.findViewById(R.id.talkback_close_btn);
        talkbackCloseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeTalkPopupWindow(true, false);
            }
        });
        mTalkRingView = (RingView) layoutView.findViewById(R.id.talkback_rv);
        mTalkBackControlBtn = (Button) layoutView.findViewById(R.id.talkback_control_btn);
        mTalkBackControlBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        switch (v.getId()) {
                            case R.id.talkback_control_btn:
                                mTalkRingView.setVisibility(View.VISIBLE);
                                mEZPlayer.setVoiceTalkStatus(true);
                                break;
                            default:
                                break;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        switch (v.getId()) {
                            case R.id.talkback_control_btn:
                                mEZPlayer.setVoiceTalkStatus(false);
                                mTalkRingView.setVisibility(View.GONE);
                                break;

                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        if (mEZDeviceInfo.isSupportTalk() == EZConstants.EZTalkbackCapability.EZTalkbackFullDuplex) {
            mTalkRingView.setVisibility(View.VISIBLE);
            mTalkBackControlBtn.setEnabled(false);
            mTalkBackControlBtn.setText(R.string.talking);
        }


        mTalkPopupWindow = new PopupWindow(layoutView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        // mTalkPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        if (showAnimation) {
            mTalkPopupWindow.setAnimationStyle(R.style.PopAnimBottom);
        }
        mTalkPopupWindow.setFocusable(false);
        mTalkPopupWindow.setOutsideTouchable(false);
//        mTalkPopupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        mTalkPopupWindow.showAsDropDown(mLlmonitor);
        // mTalkPopupWindow.setOnDismissListener(new OnDismissListener() {
        //
        // @Override
        // public void onDismiss() {
        // LogUtil.infoLog(TAG, "KEYCODE_BACK DOWN");
        // mTalkPopupWindow = null;
        // closeTalkPopupWindow();
        // }
        // });
        mTalkPopupWindow.update();
        mTalkRingView.post(new Runnable() {
            @Override
            public void run() {
                if (mTalkRingView != null) {
                    mTalkRingView.setMinRadiusAndDistance(mTalkBackControlBtn.getHeight() / 2f,
                            Utils.dip2px(mContext, 22));
                }
            }
        });
    }

    private void closeTalkPopupWindow(boolean stopTalk, boolean startAnim) {
        if (mTalkPopupWindow != null) {
            dismissPopWindow(mTalkPopupWindow);
            mTalkPopupWindow = null;
        }
        mTalkRingView = null;
        if (stopTalk)
            stopVoiceTalk(startAnim);
    }

    /**
     * 停止对讲
     *
     * @see
     * @since V2.0
     */
    private void stopVoiceTalk(boolean startAnim) {
        if (!isPlay) {
            return;
        }
        mEZPlayer.stopVoiceTalk();
        handleVoiceTalkStoped(startAnim);
    }

    private void handleVoiceTalkStoped(boolean startAnim) {
        if (mIsOnTalk) {
            mIsOnTalk = false;
        }


        if (mEZDeviceInfo.getStatus() == RealPlayStatus.STATUS_PLAY) {
            if (mEZPlayer != null) {
                if (LocalInfo.getInstance().isSoundOpen()) {
                    mEZPlayer.openSound();
                    mIvVoice.setImageResource(R.mipmap.player_voice_open);
                } else {
                    mEZPlayer.closeSound();
                    mIvVoice.setImageResource(R.mipmap.player_voice_close);
                }
            }
        }
    }

    private void dismissPopWindow(PopupWindow popupWindow) {
        if (popupWindow != null && !((Activity) mContext).isFinishing()) {
            try {
                popupWindow.dismiss();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    private void handleVoiceTalkFailed(ErrorInfo errorInfo) {
        closeTalkPopupWindow(true, false);

        switch (errorInfo.errorCode) {
            case ErrorCode.ERROR_TRANSF_DEVICE_TALKING:
                Utils.showToast(mContext, R.string.realplay_play_talkback_fail_ison);
                break;
            case ErrorCode.ERROR_TRANSF_DEVICE_PRIVACYON:
                Utils.showToast(mContext, R.string.realplay_play_talkback_fail_privacy);
                break;
            case ErrorCode.ERROR_TRANSF_DEVICE_OFFLINE:
                Utils.showToast(mContext, R.string.realplay_fail_device_not_exist);
                break;
            case ErrorCode.ERROR_TTS_MSG_REQ_TIMEOUT:
            case ErrorCode.ERROR_TTS_MSG_SVR_HANDLE_TIMEOUT:
            case ErrorCode.ERROR_TTS_WAIT_TIMEOUT:
            case ErrorCode.ERROR_TTS_HNADLE_TIMEOUT:
                Utils.showToast(mContext, R.string.realplay_play_talkback_request_timeout, errorInfo.errorCode);
                break;
            case ErrorCode.ERROR_CAS_AUDIO_SOCKET_ERROR:
            case ErrorCode.ERROR_CAS_AUDIO_RECV_ERROR:
            case ErrorCode.ERROR_CAS_AUDIO_SEND_ERROR:
                Utils.showToast(mContext, R.string.realplay_play_talkback_network_exception, errorInfo.errorCode);
                break;
            default:
                Utils.showToast(mContext, R.string.realplay_play_talkback_fail, errorInfo.errorCode);
                break;
        }
    }


    @OnClick({R.id.iv_back, R.id.tv_del, R.id.sv_realplay, R.id.iv_play, R.id.iv_pause, R.id.iv_rotate, R.id.iv_microphone, R.id.iv_camera, R.id.iv_voice})
    public void playerOnclick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
            return;
        }
        if (mEZDeviceInfo != null) {
            switch (id) {
                case R.id.tv_del:
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
                    builder.setTitle("确认删除").setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                                mPresenter.DelEzDevicePermission(mDeviceSerial);

                        }
                    }).show();
                    break;
                case R.id.iv_play:
                    if (mVerifyCode != null) {
                        mEZPlayer = mEZOpenSDK.createPlayer(mDeviceSerial, 1);
                        mPlayerHandler = new PlayerHandler();
                        mEZPlayer.setHandler(mPlayerHandler);
                        mEZPlayer.setSurfaceHold(mSurfaceView.getHolder());
                        mEZPlayer.setPlayVerifyCode(mVerifyCode);
                        mEZPlayer.startRealPlay();
                        mIvPlay.setVisibility(View.GONE);
                        mIvpause.setVisibility(View.GONE);
                        mPlayerLoadingTextView.setVisibility(View.VISIBLE);
                        mTvPrompt.setVisibility(View.GONE);
                    } else {
                        VerifyCodeInput.VerifyCodeInputDialog(mContext, new VerifyCodeInput.VerifyCodeInputListener() {
                            @Override
                            public void onInputVerifyCode(String verifyCode) {
                                mEZPlayer = mEZOpenSDK.createPlayer(mDeviceSerial, 1);
                                mPlayerHandler = new PlayerHandler();
                                mEZPlayer.setHandler(mPlayerHandler);
                                mEZPlayer.setSurfaceHold(mSurfaceView.getHolder());
                                mVerifyCode = verifyCode;
                                mEZPlayer.setPlayVerifyCode(verifyCode);
                                mEZPlayer.startRealPlay();
                                mIvPlay.setVisibility(View.GONE);
                                mIvpause.setVisibility(View.GONE);
                                mPlayerLoadingTextView.setVisibility(View.VISIBLE);
                                mTvPrompt.setVisibility(View.GONE);
                            }
                        }).show();
                    }
                    break;
                case R.id.iv_pause:
                    mEZPlayer.stopRealPlay();
                    break;
                case R.id.iv_rotate:
                    if (isPlay) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    mEZOpenSDK.controlVideoFlip(mDeviceSerial, 1, EZConstants.EZPTZDisplayCommand.EZPTZDisplayCommandFlip);
                                } catch (BaseException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                    break;
                case R.id.iv_microphone:
                    if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {

                        ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
                    } else {

                        startVoiceTalk();
                    }

                    break;
                case R.id.iv_camera:
                    onCapturePicBtnClick();
                    break;
                case R.id.iv_voice:
                    if (isPlay) {
                        onSoundBtnClick();
                    }
                    break;
            }
        } else {
            ToastUtil.shortShow("请先添加设备");
        }

    }

    private void onSoundBtnClick() {
        if (mLocalInfo.isSoundOpen()) {
            mLocalInfo.setSoundOpen(false);
            mIvVoice.setImageResource(R.mipmap.player_voice_close);
        } else {
            mLocalInfo.setSoundOpen(true);
            mIvVoice.setImageResource(R.mipmap.player_voice_open);

        }

        setRealPlaySound();
    }


    private void setRealPlaySound() {

        if (mLocalInfo.isSoundOpen()) {
            mEZPlayer.openSound();
        } else {
            mEZPlayer.closeSound();
        }
    }


    private void onCapturePicBtnClick() {


        if (!SDCardUtil.isSDCardUseable()) {
            // 提示SD卡不可用
            Utils.showToast(mContext, R.string.remoteplayback_SDCard_disable_use);
            return;
        }

        if (SDCardUtil.getSDCardRemainSize() < SDCardUtil.PIC_MIN_MEM_SPACE) {
            // 提示内存不足
            Utils.showToast(mContext, R.string.remoteplayback_capture_fail_for_memory);
            return;
        }

        if (isPlay) {
            Thread thr = new Thread() {
                @Override
                public void run() {
                    Bitmap bmp = mEZPlayer.capturePicture();
                    if (bmp != null) {
                        try {
                            mAudioPlayUtil.playAudioFile(AudioPlayUtil.CAPTURE_SOUND);

                            // 可以采用deviceSerial+时间作为文件命名，demo中简化，只用时间命名
                            java.util.Date date = new java.util.Date();
                            final String path = Environment.getExternalStorageDirectory().getPath() + "/EZOpenSDK/CapturePicture/" + String.format("%tY", date)
                                    + String.format("%tm", date) + String.format("%td", date) + "/"
                                    + String.format("%tH", date) + String.format("%tM", date) + String.format("%tS", date) + String.format("%tL", date) + ".jpg";

                            if (TextUtils.isEmpty(path)) {
                                bmp.recycle();
                                bmp = null;
                                return;
                            }
                            EZUtils.saveCapturePictrue(path, bmp);


                            MediaScanner mMediaScanner = new MediaScanner(mContext);
                            mMediaScanner.scanFile(path, "jpg");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(mContext, getResources().getString(R.string.already_saved_to_volume) + path, Toast.LENGTH_SHORT).show();
                                }
                            });
                        } catch (InnerException e) {
                            e.printStackTrace();
                        } finally {
                            if (bmp != null) {
                                bmp.recycle();
                                bmp = null;
                                return;
                            }
                        }
                    }
                    super.run();
                }
            };
            thr.start();
        }
    }

    /**
     * 设备对讲
     *
     * @see
     * @since V2.0
     */
    private void startVoiceTalk() {
        if (isPlay) {
            switch (mEZDeviceInfo.isSupportTalk()) {
                case EZTalkbackNoSupport:
                    ToastUtil.show(R.string.no_support_talk);
                    break;
                case EZTalkbackFullDuplex:
                case EZTalkbackHalfDuplex:
                    mIsOnTalk = true;
                    mEZPlayer.startVoiceTalk();
                    break;
            }
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startVoiceTalk();
                } else {
                    ToastUtil.show("请在设置中添加录音权限");
                }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mEZPlayer != null) {
            mEZPlayer.setSurfaceHold(mSurfaceView.getHolder());
            if (isPlay) {
                mEZPlayer.startRealPlay();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mEZPlayer != null) {
            mEZPlayer.release();
        }

    }
}
